package Demo_201;

/**
 * 一个实例对象  分别调用两个方法 对应同一个锁对象
 * 新new一个对象作为 锁对象  锁代码块
 * 对全局变量进行累加
 */
public class Demo_07 {
    public static void main(String[] args) throws InterruptedException {
        Count07 count1 = new Count07();
        Thread th1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count1.increase();
            }
        });
        Thread th2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //没用synchronized修饰
                count1.increase1();
            }
        });
        //启动线程
        th1.start();
        th2.start();
        //等待线程执行完毕
        th1.join();
        th2.join();
        //打印结果，预期结果为：100000
        System.out.println(count1.count);
        //符合预期
    }
}
class Count07 {

    public static int count = 0;

    Object locker = new Object();

    public void increase() {
        synchronized (locker) {
            count++;
        }
    }
    public void increase1() {
        synchronized (locker) {
            count++;
        }
    }
}